﻿
namespace Slc.Core.Entity
{
    public class JoinEntity
    {
        private OQL _mainOql;
        private string _joinType;
        private EntityBase _joinedEntity;

        public string JoinedString { get; private set; }
        public string LeftString { get; private set; }
        public string RightString { get; private set; }
        /// <summary>
        /// 以一个OQL对象关联本类
        /// </summary>
        /// <param name="mainOql"></param>
        public JoinEntity(OQL mainOql, EntityBase entity, string joinType)
        {
            this._mainOql = mainOql;
            this._joinType = joinType;
            this._joinedEntity = entity;

        }
        /// <summary>
        /// 指定要关联查询的实体类属性（内部对应字段）
        /// </summary>
        /// <param name="field1">主实体类的主键属性</param>
        /// <param name="field2">从实体类的外键属性</param>
        /// <returns></returns>
        public OQL On(object field1, object field2)
        {
            TableNameField tnfRight = this._mainOql.fieldStack.Pop();
            TableNameField tnfLeft = this._mainOql.fieldStack.Pop();
            LeftString = this._mainOql.GetOqlFieldName(tnfLeft);
            RightString = this._mainOql.GetOqlFieldName(tnfRight);

            this.JoinedString = string.Format("\r\n{0} [{1}] {2}  ON {3} ={4} ", _joinType,
                _joinedEntity.GetTableName(),
                this._mainOql.GetTableAliases(_joinedEntity),
                LeftString,
                RightString);
            this._mainOql.oqlString += this.JoinedString;
            return this._mainOql;
        }
        /// <summary>
        /// （OQL内部使用）添加要关联的字段名
        /// </summary>
        /// <param name="fieldName"></param>
        public void AddJoinFieldName(string fieldName)
        {
            if (string.IsNullOrEmpty(this.LeftString))
                this.LeftString = fieldName;
            else if (string.IsNullOrEmpty(this.RightString))
                this.RightString = fieldName;
        }
    }
}
